package com.feng.cloud.auth.translator;

import com.feng.cloud.common.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

import static com.feng.cloud.common.exception.auth.AuthStatus.REFRESH_TOKEN_INVALID;

/**
 * @ClassName AuthWebResponseExceptionTranslator
 * @Description 异常翻译器(翻译spring security异常)
 * @Author Better Feng
 * @Date 2019/12/17 16:44
 * @Version 1.0
 **/
@Slf4j
@Component
public class AuthWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
    /**
     *
     * @param e 被翻译的异常
     * @return BaseResponse
     * @throws Exception 异常
     * https://blog.csdn.net/qq_31063463/article/details/83752459
     */
    @Override
    public ResponseEntity<BaseResponse> translate(Exception e) throws Exception {
        ResponseEntity.BodyBuilder status = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        BaseResponse response = new BaseResponse(500,"认证失败");
        log.error(response.getMessage(),response);
        if (e instanceof UnsupportedGrantTypeException) {
            return status.body(response.message("不支持该认证类型"));
        } else if (e instanceof InvalidTokenException
                && StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token (expired)")) {
            response.setStatus(REFRESH_TOKEN_INVALID.getStatus());
            return status.body(response.message("刷新令牌已过期，请重新登录"));
        } else if (e instanceof InvalidScopeException) {
            return status.body(response.message("不是有效的scope值"));
        } else if (e instanceof InvalidGrantException) {
            if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token")) {
                return status.body(response.message("refresh token无效"));
            }else if (StringUtils.containsIgnoreCase(e.getMessage(), "locked")) {
                return status.body(response.message("用户已被锁定，请联系管理员"));
            } else if ((StringUtils.containsIgnoreCase(e.getMessage(), "用户帐号已被锁定"))) {
                return status.body(response.message("用户已被锁定，请联系管理员"));
            }
            return status.body(response.message("用户名或密码错误"));
        }
        return status.body(response);
    }
}
